package tempo.timing;

import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class ResultActivity extends Activity
{
	private static class EfficientAdapter extends BaseAdapter
	{
		private LayoutInflater mInflater;
		private ArrayList<Rider> mRiders;

		public EfficientAdapter(Context context, ArrayList<Rider> riders)
		{
			mInflater = LayoutInflater.from(context);
			mRiders = riders;
		}

		public int getCount()
		{
			return mRiders.size();
		}

		public Object getItem(int position)
		{
			return position;
		}

		public long getItemId(int position)
		{
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			ViewHolder holder;
			if (convertView == null)
			{
				convertView = mInflater.inflate(R.layout.listviewresult, null);
				holder = new ViewHolder();
				holder.txtNumber = (TextView) convertView.findViewById(R.id.txtNumber);
				holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
				holder.txtResult = (TextView) convertView.findViewById(R.id.txtResult);
				convertView.setTag(holder);
				convertView.setBackgroundColor((position & 1) == 1 ? Color.WHITE : Color.LTGRAY);

			} else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			holder.txtNumber.setText(mRiders.get(position).getStartNumber());
			holder.txtName.setText(mRiders.get(position).getRiderName());
			holder.txtResult.setText(mRiders.get(position).GetStringResult());
			
			return convertView;
		}

		static class ViewHolder
		{
			TextView txtNumber;
			TextView txtName;
			TextView txtResult;
		}
	}
	
	private ListView lstResult;
	private ArrayList<Rider> mRiders;
	private Button btnRefresh;

	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.result);
		
		lstResult = (ListView) findViewById(R.id.lstResult);
		btnRefresh = (Button) findViewById(R.id.btnRefresh);
		btnRefresh.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				refreshList();
			}
		});
	}
	
	protected void onResume()
	{
		super.onResume();
		refreshList();
	}

	private void refreshList()
	{
		mRiders = Race.getCurrent().GetRiders();
		Collections.sort(mRiders);
		lstResult.setAdapter(new EfficientAdapter(this, mRiders));
	}

}
